package com.example.seataStorage.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.seataStorage.common.enums.RspStatusEnum;
import com.example.seataStorage.common.response.ObjectResponse;
import com.example.seataStorage.entity.Storage;
import com.example.seataStorage.mapper.StorageMapper;
import org.springframework.stereotype.Service;

@Service
public class StorageService {

    private final StorageMapper storageMapper;

    public StorageService(StorageMapper storageMapper) {
        this.storageMapper = storageMapper;
    }

    /**
     * 减库存
     * @param commodityCode 商品编号
     * @param count 购买数量
     */
    public ObjectResponse<Object> deduct(String commodityCode, int count){
        ObjectResponse<Object> response = new ObjectResponse<>();
        QueryWrapper<Storage> wrapper = new QueryWrapper<>();
        wrapper.setEntity(new Storage().setCommodityCode(commodityCode));
        Storage storage = storageMapper.selectOne(wrapper);
        storage.setCount(storage.getCount()-count);
        int result = storageMapper.updateById(storage);
        if (result > 0){
            response.setStatus(RspStatusEnum.SUCCESS.getCode());
            response.setMessage(RspStatusEnum.SUCCESS.getMessage());
            return response;
        }
        response.setStatus(RspStatusEnum.FAIL.getCode());
        response.setMessage(RspStatusEnum.FAIL.getMessage());
        return  response;
    }
}
